package com.cuitrip.business.tripservice;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cuitrip.app.util.FontManager;
import com.cuitrip.service.R;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBuffer;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 * Created by MiJack on 2015/10/30.
 */
public class SearchGoogleMapActivity extends AppCompatActivity {
    private static final int PLACE_PICKER_REQUEST = 22;
    Toolbar toolbar;
    EditText search;
    ListView listView;
    GoogleApiClient mGoogleApiClient;
    ProgressBar progressBar;
    private PredictionAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Hide the window title.
        FontManager.changeActivityFonts(this);
        setContentView(R.layout.activity_search_google_map);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        search = (EditText) findViewById(R.id.search);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        listView = (ListView) findViewById(R.id.listView);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        search.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search(v.getText().toString());
                    handled = true;
                }
                return handled;
            }
        });
        mGoogleApiClient = new GoogleApiClient
                .Builder(this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .build();
        adapter = new PredictionAdapter();
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Model model = adapter.getItem(position);
                PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
                if (model.viewport != null) {
                    builder = builder.setLatLngBounds(model.viewport);
                } else {
                    double latitude = model.latLng.latitude;
                    double longitude = model.latLng.longitude;
                    double delta = 0.001;
                    builder = builder.setLatLngBounds(new LatLngBounds(new LatLng(latitude - delta, longitude - delta), new LatLng(latitude + delta, longitude + delta)));
                }
                try {
                    startActivityForResult(builder.build(SearchGoogleMapActivity.this), PLACE_PICKER_REQUEST);
                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();
                } catch (GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        mGoogleApiClient.disconnect();
        super.onStop();
    }


    private void search(String search) {
        progressBar.setVisibility(View.VISIBLE);
        listView.setVisibility(View.INVISIBLE);
        PendingResult<AutocompletePredictionBuffer> result = Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, search, null, null);
        result.setResultCallback(new ResultCallback<AutocompletePredictionBuffer>() {
            @Override
            public void onResult(AutocompletePredictionBuffer autocompletePredictions) {
                Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
                List<String> list = new ArrayList<>();
                while (iterator.hasNext()) {
                    AutocompletePrediction prediction = iterator.next();
                    list.add(prediction.getPlaceId());
                }
                if(list.size()==0){
                    Toast.makeText(SearchGoogleMapActivity.this, R.string.feedback_no_results,Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                    return;
                }
                Places.GeoDataApi.getPlaceById(mGoogleApiClient, list.toArray(new String[list.size()]))
                    .setResultCallback(new ResultCallback<PlaceBuffer>() {
                        @Override
                        public void onResult(PlaceBuffer places) {
                            List<Model> models = new ArrayList<>();
                            Iterator<Place> placeIterator = places.iterator();
                            while (placeIterator.hasNext()) {
                                Place place = placeIterator.next();
                                Model model = new Model(place.getAddress().toString(),
                                        place.getId(), place.getLatLng(), place.getLocale(), place.getName().toString(), place.getPhoneNumber().toString(), place.getPlaceTypes(), place.getPriceLevel(),
                                        place.getRating(), place.getViewport(), place.getWebsiteUri());
                                models.add(model);
                            }
                            bindDatas(models);
                        }
                    });
                autocompletePredictions.release();
            }
        });
    }

    private void bindDatas(List<Model> list) {
        adapter.setList(list);
        listView.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.ct_cancel, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            return true;
        } else if (item.getItemId() == R.id.action_cancel) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK, data);
                finish();
            }
        }
    }

    class Model {
        public String address;
        public String id;
        public LatLng latLng;
        public Locale locale;
        public String name;
        public String phoneNumber;
        public List<Integer> placeTypes;
        public int priceLevel;
        public float rating;
        public LatLngBounds viewport;
        public Uri websiteUri;

        public Model(String address, String id, LatLng latLng, Locale locale, String name, String phoneNumber, List<Integer> placeTypes, int priceLevel, float rating, LatLngBounds viewport, Uri websiteUri) {
            this.address = address;
            this.id = id;
            this.latLng = latLng;
            this.locale = locale;
            this.name = name;
            this.phoneNumber = phoneNumber;
            this.placeTypes = placeTypes;
            this.priceLevel = priceLevel;
            this.rating = rating;
            this.viewport = viewport;
            this.websiteUri = websiteUri;
        }
    }

    private class PredictionAdapter extends BaseAdapter {

        List<Model> list;

        public PredictionAdapter() {
        }

        public void setList(List<Model> list) {
            this.list = list;
            this.notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Model getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Model model = getItem(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2, parent, false);
            }
            ((TextView) convertView.findViewById(android.R.id.text1)).setText(model.name);
            ((TextView) convertView.findViewById(android.R.id.text2)).setText(model.address);
            convertView.setTag(model);
            return convertView;
        }
    }
}
